import os
import json
from docx import Document
def get_no_license_explain_software(docs):
    softwares = []
    for doc in docs:
        document = Document(doc)
        explain_flag = False
        software = None
        for index, paragraph in enumerate(document.paragraphs):
            if paragraph.text.startswith('Software'):
                software_lines = paragraph.text.split(':')
                if len(software_lines) < 2:
                    print(f'abnormal doc:{doc}')
                    continue
                else:
                    software = software_lines[1]
            if paragraph.text.startswith('License'):
                for remain_paragraph in document.paragraphs[index+1:]:
                    if remain_paragraph.text and remain_paragraph.text != '\n' and remain_paragraph.text != '\t':
                        if remain_paragraph.text.startswith('Written Offer'):
                            explain_flag = False
                        else:
                            explain_flag = True
                        break
        print(f'explain_flag={explain_flag},software={software}')
        if not explain_flag and software:
            softwares.append(software)
            softwares.append('\n')

    return softwares

def list_docs():
    all_doc = []
    local_dirname = os.path.abspath('.')
    for root, _, file_names in os.walk(local_dirname):
        for file_name in file_names:
            if file_name.endswith('.docx') and not file_name.startswith('~'):
                all_doc.append(os.path.join(root, file_name))
    return all_doc

def write_software(softwares):
    with open('no_license_software.json', 'w+') as f:
        f.writelines(softwares)

if __name__ == "__main__":
    all_doc = list_docs()
    softwares = get_no_license_explain_software(all_doc)
    write_software(softwares)